package ctrs.controller;

import com.alibaba.fastjson.JSON;
import ctrs.bean.Knowledge;
import ctrs.bean.QueryInfo;
import ctrs.dao.KnowledgeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
public class KnowledgeController {

    @Autowired
    KnowledgeDao knowledgeDao;

    @CrossOrigin
    @RequestMapping("/allKnowledge")
    public String getAllKnowledge(QueryInfo queryInfo){
        System.out.println(queryInfo);
        List<Knowledge> knowledge = knowledgeDao.getAllKnowledge("%"+queryInfo.getQuery()+"%");
        HashMap<String, Object> res = new HashMap<>();
        res.put("data",knowledge);
        System.out.println("res:"+ res);
        String knowledge_json = JSON.toJSONString(res);
        return knowledge_json;
    }

    @RequestMapping("/addKnowledge")
    public String addKnowledge(@RequestBody Knowledge knowledge){
        int i = knowledgeDao.addKnowledge(knowledge);
        return i>0?"success":"error";
    }

    @RequestMapping("/getUpdateKnowledge")
    public String getUpdateKnowledge(String knowledgeId) {
        System.out.println("编号:" + knowledgeId);
        Knowledge updateKnowledge = knowledgeDao.getUpdateKnowledge(knowledgeId);
        String users_json = JSON.toJSONString(updateKnowledge);
        return users_json;
    }

    @RequestMapping("/editKnowledge")
    public String editKnowledge(@RequestBody Knowledge knowledge) {
        System.out.println(knowledge);
        int i = knowledgeDao.editKnowledge(knowledge);
        String str = i > 0 ? "success" : "error";
        return str;
    }

    @RequestMapping("/deleteKnowledge")
    public String deleteKnowledge(String knowledgeId){
        System.out.println(knowledgeId);
        int i = knowledgeDao.deleteKnowledge(knowledgeId);
        String str = i > 0 ? "success" : "error";
        return str;
    }

}
